package com.example.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.example.service.MsmService;
import com.example.utils.ConstantMsmUtils;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送短信的方法
     *
     * @param param 验证码
     * @param phone 手机号
     * @return
     */
    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if ((StringUtils.isEmpty(phone))) return false;

        DefaultProfile profile = DefaultProfile.getProfile(ConstantMsmUtils.ACCESS_REGION_ID, ConstantMsmUtils.ACCESS_KEY_ID, ConstantMsmUtils.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关参数
        SendSmsRequest request = new SendSmsRequest();

        request.setPhoneNumbers(phone); //手机号码
        request.setSignName("阿里云短信测试"); //签名的名称
        request.setTemplateCode(ConstantMsmUtils.ACCESS_TEMPLATE_CODE); //模板的code
        request.setTemplateParam(JSONObject.toJSONString(param)); //验证码数据，转换json数据传递

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            if ("OK".equals(response.getCode())) {
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

        return false;
    }
}
